package com.ettractions.kiosk.mediators
{
	import com.ettractions.kiosk.components.BrochureSendToMeView;
	import com.ettractions.kiosk.events.BrochureSelectEvent;
	
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	
	import mx.controls.Alert;
	import mx.events.ValidationResultEvent;
	import mx.validators.EmailValidator;
	
	import org.robotlegs.mvcs.Mediator;
	
	public class BrochureSendToMeMediator extends Mediator
	{
		[Inject]
		public var view:BrochureSendToMeView;
		
		private var _emailValidator:EmailValidator = new EmailValidator();
		
		private var _emailTextField:TextField;
		
		override public function onRegister():void
		{
			eventDispatcher.addEventListener(BrochureSelectEvent.BROCHURE_SELECTED, handleBrochureSelected);			
			
			_emailValidator.addEventListener(ValidationResultEvent.VALID, handleEmailValid);
			_emailValidator.addEventListener(ValidationResultEvent.INVALID, handleEmailInvalid);
			
			_emailTextField = Sprite(Loader(Sprite(view.keyboard.getChildAt(0)).getChildAt(0)).getChildAt(0))["main"].mcOutput.mcTxt.txt;
			
			view.sendButton.addEventListener(MouseEvent.CLICK, handleSendButtonClick);
		}
		
		private function handleBrochureSelected(event:BrochureSelectEvent):void
		{
			if (event.brochure != null)
				view.data = event.brochure;
		}
		
		private function handleSendButtonClick(event:MouseEvent):void
		{
			_emailValidator.validate(_emailTextField.text);
		}
		
		private function handleEmailValid(event:ValidationResultEvent):void
		{
			Alert.show("Thanks!", "E-mail sent.", Alert.OK);
		}
		
		private function handleEmailInvalid(event:ValidationResultEvent):void
		{
			Alert.show("Please enter a valid e-mail address", "Invalid E-mail Address", Alert.OK);
		}		
	}
}